package product

import (
	"context"
	"net/http"

	"go-zero-admin/apps/modules/iot/cmd/api/internal/svc"
	"go-zero-admin/apps/modules/iot/cmd/api/internal/types"
	"go-zero-admin/apps/modules/iot/cmd/rpc/iotpb"
	"go-zero-admin/pkg/ctxdata"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
)

type ListProductLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	r      *http.Request
}

func NewListProductLogic(ctx context.Context, svcCtx *svc.ServiceContext, r *http.Request) *ListProductLogic {
	return &ListProductLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		r:      r,
	}
}

func (l *ListProductLogic) ListProduct(req *types.ListProductReq) (resp *types.ListProductResp, err error) {
	productListResp, err := l.svcCtx.ProductRpc.GetProductList(l.ctx, &iotpb.GetProductListReq{
		Page: &iotpb.PageReq{
			DateRange: req.DateRange,
			PageNum:   req.PageNum,
			PageSize:  req.PageSize,
			IsPage:    true,
		},
		DeptId:          req.DeptId,
		Name:            req.Name,
		State:           req.State,
		DeviceType:      req.DeviceType,
		IsDataScope:     true,
		DataScopeUserId: ctxdata.GetUidFromCtx(l.ctx),
	})
	if err != nil {
		return nil, err
	}

	// 处理数据
	productList := make([]*types.IotProduct, 0)
	for _, v := range productListResp.GetList() {
		var product types.IotProduct
		_ = copier.Copy(&product, v)
		productList = append(productList, &product)
	}

	return &types.ListProductResp{
		PageResp: &types.PageResp{
			CurrentPage: productListResp.GetPage().GetCurrent(),
			Total:       productListResp.GetPage().GetTotal(),
		},
		List: productList,
	}, nil
}
